# 设置源文件夹和目标文件夹路径
$sourceFolder = "F:\MedAi\pancreas_all"
$destinationFolder = "F:\MedAi\pancreas_ok\masks"

# 定义要查找的文件名列表
$fileNamesToFind = @("DWI", "T1_A", "T1_D", "T1_PRE", "T1_V", "T2")

# 获取所有三级子文件夹
$thirdLevelFolders = Get-ChildItem -Path $sourceFolder -Recurse -Directory | 
                     Where-Object { $_.FullName.Split('\').Count -eq ($sourceFolder.Split('\').Count + 3) }

foreach ($folder in $thirdLevelFolders) {
    # 获取该目录下的所有 .nii.gz 文件
    $niiFiles = Get-ChildItem -Path $folder.FullName -Filter "*.nii.gz"

    foreach ($file in $niiFiles) {
        # 检查文件名（去除扩展名）是否在指定的名称列表中
        # $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($file.Name)

        $string = $file.Name

        $fileNameWithoutExtension = $string.Substring(0, $string.Length - 7)

        # Debug 文件名正确
        # Write-Host "$fileNameWithoutExtension"
        # break

        if ($fileNamesToFind -contains $fileNameWithoutExtension) {
            # 获取当前文件的一级目录名称

            $splitStrings = $folder.FullName -split '\\'
            $1Folder = $splitStrings[-3]

            # Write-Host "$1Folder"

            # 生成新文件名
            $newFileName = "${1Folder}+$string"

            # Write-Host "$newFileName"

            # 设置目标路径
            $destinationPath = Join-Path -Path $destinationFolder -ChildPath $newFileName

            # 复制文件到目标文件夹
            Copy-Item -Path $file.FullName -Destination $destinationPath -Force
            Write-Host "已复制文件: $($file.FullName) 到 $destinationPath"
        }
    }
    # test once
    # break
}
